package com.lanou.dormitory.web;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lanou.dormitory.entity.Company;
import com.lanou.dormitory.service.CompanyService;
import com.lanou.dormitory.util.ResultUtil;

@Controller
public class CompanyController {
	@Autowired
	private CompanyService companyService;
	
	@RequestMapping("/company/delCompany/{cid}")
	@ResponseBody
	public ResultUtil del(@PathVariable Integer cid){
		//根据cid删除
		companyService.delById(cid);
		return ResultUtil.ok();
	}
	
	@RequestMapping("/company/updCompany")
	@ResponseBody
	public ResultUtil update(Company com){
		//进行修改了 mapper  service
		try {
			companyService.update(com);
			return ResultUtil.ok();
		} catch (Exception e) {
			e.printStackTrace();
			return ResultUtil.error("修改失败");
		}
	}
	
	@RequestMapping("/company/editCompany/{cid}")
	public String toEdit(@PathVariable Integer cid,
			HttpServletRequest req){
		//通过cid获取公司信息
		Company com = companyService.getById(cid);
		//获取的公司信息放到request范围中
		req.setAttribute("aClass", com);
		
		return "/jsp/company/editCompany";
	}
	
	@RequestMapping("/company/insCompany")
	public ResultUtil addCompany(String companyName,String companyNote){
		//开始入库
		try {
			companyService.add(companyName, companyNote);
			return ResultUtil.ok();
		} catch (Exception e) {
			e.printStackTrace();
			return ResultUtil.error("添加失败");
		}
	}
	
	@RequestMapping("/company/checkCompanyName/{cname}")
	@ResponseBody
	public ResultUtil checkName(@PathVariable String cname){
		//根据cname查询 看看数据库中是否已经有一样的公司名称了
		Company c = companyService.getCompayByName(cname);
		if(c==null){
			return ResultUtil.ok();
		}else{
			return ResultUtil.error("公司名称已存在");
		}
	}
	
	@RequestMapping("/company/addCompany")
	public String toAdd(){
		return "/jsp/company/addCompany";
	}

	
	
	
	
	@RequestMapping("/company/companyList")
	public String toCompanyList(){
		return "/jsp/company/companyList";
	}
	
	@RequestMapping("/company/getCompanyList")
	@ResponseBody
	public ResultUtil getList(Integer page,Integer limit){
		
		PageHelper.startPage(page, limit);
		List<Company> list = companyService.getAll();//所有的
		
		PageInfo<Company> info = new PageInfo<>(list);
		
		Long total = info.getTotal();//总条数
		List pagelist = (List) info.getList();//只显示10条数据
		
		ResultUtil result = new ResultUtil();//处理返回结果的
		result.setCode(0);
		result.setMsg("");
		result.setCount(total);
		result.setData(pagelist);
		
		return result;
	}
}
